package com.electric.qrapp.utils.function

import android.graphics.Bitmap
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.ViewGroup
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.electric.qrapp.R
import com.electric.qrapp.utils.system.showLog
import com.electric.qrapp.utils.view.LoadingUtils
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView.setWebContentsDebuggingEnabled
import com.tencent.smtt.sdk.WebViewClient


/**
 *@author created by WA03675
 *@date  2021-08-11 16:26
 *@des 扩展函数
 */

//初始化webView
fun com.tencent.smtt.sdk.WebView.init(
    activity: AppCompatActivity,
    container: ViewGroup?,
    loadingUtils: LoadingUtils?,
    isNeedClear: Boolean = true,
) {


    settings.run {


        //自适应
        useWideViewPort = true
        loadWithOverviewMode = true

        domStorageEnabled = true

        //缩放操作
        setSupportZoom(false)
        builtInZoomControls = false
        displayZoomControls = true

        //关闭webview中缓存
        cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        //设置可以访问文件
        allowFileAccess = true
        //支持通过JS打开新窗口
        javaScriptCanOpenWindowsAutomatically = true
        //支持自动加载图片
        loadsImagesAutomatically = true
        //设置编码格式
        defaultTextEncodingName = "UTF-8"

        //设置文本字体的最小值(1~72)
        minimumFontSize = 8
        //设置文本字体默认的大小
        defaultFontSize = 16

        javaScriptEnabled = true



        settings.mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW;
        settings.setAppCacheMaxSize(50 * 1024 * 1024);
        //图片不显示问题
        settings.setBlockNetworkImage(false);// API 19

        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.mixedContentMode = WebSettings.LOAD_NORMAL;
        setWebContentsDebuggingEnabled(true);

        settings.useWideViewPort = true;

        settings.mediaPlaybackRequiresUserGesture = false;


    }

    let {


        webViewClient = object : WebViewClient() {
            override fun onPageStarted(
                p0: com.tencent.smtt.sdk.WebView?,
                p1: String?,
                p2: Bitmap?
            ) {
                super.onPageStarted(p0, p1, p2)
                loadingUtils?.showLoading(activity, true)
            }

            override fun onPageFinished(p0: com.tencent.smtt.sdk.WebView?, p1: String?) {
                super.onPageFinished(p0, p1)
                loadingUtils?.showLoading(activity, false)
                showLog("加载结束->${p1.toString()}")
            }

            override fun onReceivedError(
                p0: com.tencent.smtt.sdk.WebView?,
                p1: com.tencent.smtt.export.external.interfaces.WebResourceRequest?,
                p2: com.tencent.smtt.export.external.interfaces.WebResourceError?
            ) {
                super.onReceivedError(p0, p1, p2)
                loadingUtils?.showLoading(activity, false)
                showLog("加载失败->${GsonUtils.gsonString(p2)}")
            }


            override fun shouldOverrideUrlLoading(
                p0: com.tencent.smtt.sdk.WebView?,
                p1: String?
            ): Boolean {
                return super.shouldOverrideUrlLoading(p0, p1)
            }
        }


    }


    activity.lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_RESUME -> {
                    onResume()
                }
                Lifecycle.Event.ON_PAUSE -> {
                    onPause()
                }
                Lifecycle.Event.ON_DESTROY -> {
                    container?.removeView(this@init)
                    if (isNeedClear) {
                        clearCache(true)
                        clearHistory()
                        clearFormData()
                        destroy()
                    }
                }
            }
        }

    })

}

fun TextView.addStar() {
    if (text.isNotBlank()) {
        val span = SpannableString("*$text")
        span.setSpan(
            ForegroundColorSpan(ActivityCompat.getColor(context, R.color.red)),
            0,
            1,
            Spannable.SPAN_INCLUSIVE_EXCLUSIVE
        )
        text = span
    }
}




